using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Core : MonoBehaviour
{
    private readonly List<CoreComponent> _corecomponents = new();
    private CollisionSenses _collisions;
    private KnockBackReceiver _combat;

    private Movement _movement;

    public Movement Movement
    {
        get => GenericNotImplementError<Movement>.TryGet(_movement, transform.parent.name);
        private set => _movement = value;
    }

    public CollisionSenses Collision
    {
        get => GenericNotImplementError<CollisionSenses>.TryGet(_collisions, transform.parent.name);
        private set => _collisions = value;
    }

    public KnockBackReceiver Combat
    {
        get => GenericNotImplementError<KnockBackReceiver>.TryGet(_combat, transform.parent.name);
        private set => _combat = value;
    }

    private void Awake()
    {
        Movement = GetComponentInChildren<Movement>();
        Collision = GetComponentInChildren<CollisionSenses>();
        Combat = GetComponentInChildren<KnockBackReceiver>();
    }

    public void LoginUpdate()
    {
        foreach (ILogicupdateable component in _corecomponents) component.LogicUpdate();
    }

    public void AddCoreComponent(CoreComponent component)
    {
        _corecomponents.Add(component);
    }

    public T GetCoreComponent<T>() where T : CoreComponent
    {
        var comp = _corecomponents.OfType<T>().FirstOrDefault();

        if (comp)
            return comp;
        comp = GetComponentInChildren<T>();
        if (comp)
            return comp;
        Debug.LogWarning($"{typeof(T)} not found on {transform.parent.name}");
        return null;
    }
}